package com.hzt.agprosaleplatform.service.impl;

import com.hzt.agprosaleplatform.common.CustomResponse;
import com.hzt.agprosaleplatform.dto.MemoryChatMessageDTO;
import com.hzt.agprosaleplatform.dto.MemoryChatSessionDTO;
import com.hzt.agprosaleplatform.dto.MemorySendMessageDTO;
import com.hzt.agprosaleplatform.entity.MemoryChatMessage;
import com.hzt.agprosaleplatform.entity.MemoryChatSession;
import com.hzt.agprosaleplatform.entity.Shop;
import com.hzt.agprosaleplatform.entity.User;
import com.hzt.agprosaleplatform.mapper.ShopMapper;
import com.hzt.agprosaleplatform.mapper.UserMapper;
import com.hzt.agprosaleplatform.service.MemoryChatService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 内存存储的聊天服务实现类
 */
@Service
public class MemoryChatServiceImpl implements MemoryChatService {
    
    // 使用ConcurrentHashMap存储会话数据
    private final ConcurrentHashMap<String, MemoryChatSession> sessionMap = new ConcurrentHashMap<>();
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private ShopMapper shopMapper;

    @Override
    public CustomResponse contactCustomerService(String buyerId, String shopId) {
        try {
            // 检查用户是否存在
            User buyer = userMapper.selectById(buyerId);
            if (buyer == null) {
                return new CustomResponse(404, "买家不存在", null);
            }
            
            // 检查店铺是否存在
            Shop shop = shopMapper.selectById(shopId);
            if (shop == null) {
                return new CustomResponse(404, "店铺不存在", null);
            }
            
            String sessionId = buyerId + "_" + shopId;
            
            // 检查是否已存在会话
            if (sessionMap.containsKey(sessionId)) {
                MemoryChatSession existingSession = sessionMap.get(sessionId);
                MemoryChatSessionDTO dto = convertToSessionDTO(existingSession);
                return new CustomResponse(200, "会话已存在", dto);
            }
            
            // 创建新会话
            MemoryChatSession newSession = new MemoryChatSession(buyerId, shopId, buyer.getUsername(), shop.getShopName());
            sessionMap.put(sessionId, newSession);
            
            MemoryChatSessionDTO dto = convertToSessionDTO(newSession);
            return new CustomResponse(200, "联系客服成功", dto);
            
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "联系客服失败", null);
        }
    }

    @Override
    public CustomResponse getBuyerSessions(String buyerId) {
        try {
            List<MemoryChatSessionDTO> sessionDTOs = sessionMap.values().stream()
                    .filter(session -> session.getBuyerId().equals(buyerId))
                    .map(this::convertToSessionDTO)
                    .collect(Collectors.toList());
            
            return new CustomResponse(200, "获取买家会话列表成功", sessionDTOs);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "获取买家会话列表失败", null);
        }
    }

    @Override
    public CustomResponse getShopSessions(String shopId) {
        try {
            List<MemoryChatSessionDTO> sessionDTOs = sessionMap.values().stream()
                    .filter(session -> session.getShopId().equals(shopId))
                    .map(this::convertToSessionDTO)
                    .collect(Collectors.toList());
            
            return new CustomResponse(200, "获取店铺会话列表成功", sessionDTOs);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "获取店铺会话列表失败", null);
        }
    }

    @Override
    public CustomResponse sendMessage(MemorySendMessageDTO sendMessageDTO) {
        try {
            String sessionId = sendMessageDTO.getSessionId();
            
            if (!sessionMap.containsKey(sessionId)) {
                return new CustomResponse(404, "会话不存在", null);
            }
            
            MemoryChatSession session = sessionMap.get(sessionId);
            
            // 创建新消息
            MemoryChatMessage message = new MemoryChatMessage(
                    sessionId,
                    sendMessageDTO.getSenderId(),
                    sendMessageDTO.getSenderName(),
                    sendMessageDTO.getReceiverId(),
                    sendMessageDTO.getReceiverName(),
                    sendMessageDTO.getContent()
            );
            
            // 添加到会话消息列表
            session.getMessages().add(message);
            session.setLastMessageTime(LocalDateTime.now());
            
            MemoryChatMessageDTO dto = convertToMessageDTO(message);
            return new CustomResponse(200, "发送消息成功", dto);
            
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "发送消息失败", null);
        }
    }

    @Override
    public CustomResponse getSessionMessages(String sessionId) {
        try {
            if (!sessionMap.containsKey(sessionId)) {
                return new CustomResponse(404, "会话不存在", null);
            }
            
            MemoryChatSession session = sessionMap.get(sessionId);
            List<MemoryChatMessageDTO> messageDTOs = session.getMessages().stream()
                    .map(this::convertToMessageDTO)
                    .collect(Collectors.toList());
            
            return new CustomResponse(200, "获取消息列表成功", messageDTOs);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "获取消息列表失败", null);
        }
    }

    @Override
    public CustomResponse markMessageAsRead(String messageId, String readerId) {
        try {
            // 查找消息所在的会话
            for (MemoryChatSession session : sessionMap.values()) {
                for (MemoryChatMessage message : session.getMessages()) {
                    if (message.getMessageId().equals(messageId)) {
                        // 检查阅读者是否有权限阅读此消息
                        if (message.getReceiverId().equals(readerId)) {
                            message.setIsRead(true);
                            MemoryChatMessageDTO dto = convertToMessageDTO(message);
                            return new CustomResponse(200, "标记已读成功", dto);
                        } else {
                            return new CustomResponse(403, "无权限阅读此消息", null);
                        }
                    }
                }
            }
            
            return new CustomResponse(404, "消息不存在", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "标记已读失败", null);
        }
    }

    @Override
    public CustomResponse getBuyerUnreadCount(String buyerId) {
        try {
            long unreadCount = sessionMap.values().stream()
                    .filter(session -> session.getBuyerId().equals(buyerId))
                    .flatMap(session -> session.getMessages().stream())
                    .filter(message -> message.getReceiverId().equals(buyerId) && !message.getIsRead())
                    .count();
            
            return new CustomResponse(200, "获取未读消息数成功", unreadCount);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "获取未读消息数失败", null);
        }
    }

    @Override
    public CustomResponse getShopUnreadCount(String shopId) {
        try {
            long unreadCount = sessionMap.values().stream()
                    .filter(session -> session.getShopId().equals(shopId))
                    .flatMap(session -> session.getMessages().stream())
                    .filter(message -> message.getReceiverId().equals(shopId) && !message.getIsRead())
                    .count();
            
            return new CustomResponse(200, "获取未读消息数成功", unreadCount);
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "获取未读消息数失败", null);
        }
    }

    @Override
    public CustomResponse closeSession(String sessionId) {
        try {
            if (sessionMap.containsKey(sessionId)) {
                sessionMap.remove(sessionId);
                return new CustomResponse(200, "关闭会话成功", null);
            } else {
                return new CustomResponse(404, "会话不存在", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CustomResponse(500, "关闭会话失败", null);
        }
    }
    
    // 转换会话实体为DTO
    private MemoryChatSessionDTO convertToSessionDTO(MemoryChatSession session) {
        MemoryChatSessionDTO dto = new MemoryChatSessionDTO();
        BeanUtils.copyProperties(session, dto);
        
        // 计算未读消息数
        long unreadCount = session.getMessages().stream()
                .filter(message -> !message.getIsRead())
                .count();
        dto.setUnreadCount((int) unreadCount);
        
        // 设置最后一条消息
        if (!session.getMessages().isEmpty()) {
            MemoryChatMessage lastMessage = session.getMessages().get(session.getMessages().size() - 1);
            dto.setLastMessage(lastMessage.getContent());
        }
        
        return dto;
    }
    
    // 转换消息实体为DTO
    private MemoryChatMessageDTO convertToMessageDTO(MemoryChatMessage message) {
        MemoryChatMessageDTO dto = new MemoryChatMessageDTO();
        BeanUtils.copyProperties(message, dto);
        return dto;
    }
}